package com.neusoft.yiyang.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.neusoft.yiyang.common.entity.user.Role;
import com.neusoft.yiyang.common.entity.user.User;
import com.neusoft.yiyang.user.mapper.RoleMapper;
import com.neusoft.yiyang.user.mapper.UserMapper;
import com.neusoft.yiyang.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    // 注入密码编码器
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public List<Map<String, Object>> getAllUsersWithRole() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_deleted", 0);
        List<User> users = userMapper.selectList(queryWrapper);
        List<Map<String, Object>> result = new ArrayList<>();
        for (User user : users) {
            Role role = roleMapper.selectById(user.getRoleId());
            Map<String, Object> map = new HashMap<>();
            map.put("user", user);
            map.put("roleName", role.getRoleName());
            result.add(map);
        }
        return result;
    }

    @Override
    public List<User> getAllUsers() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public User getUserById(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("username", username).eq("is_deleted", 0));
    }

    @Override
    public Map<String, Object> createUser(User user) {
        Map<String, Object> result = new HashMap<>();

        String phone = user.getPhone();
        if (phone == null || phone.length() < 6) {
            throw new IllegalArgumentException("手机号长度不足");
        }
        // 初始密码为手机号后六位（明文）
        String rawPassword = phone.substring(phone.length() - 6);
        // 对初始密码进行加密
        String encodedPassword = passwordEncoder.encode(rawPassword);

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        User existingUser = userMapper.selectOne(queryWrapper);

        if (existingUser != null) {
            if (existingUser.getIsDeleted() == 1) {
                // 恢复用户时设置加密后的密码
                existingUser.setIsDeleted(0);
                existingUser.setUsername(user.getUsername());
                existingUser.setName(user.getName());
                existingUser.setPassword(encodedPassword); // 使用加密密码
                existingUser.setStatus(user.getStatus());
                existingUser.setRoleId(user.getRoleId());
                existingUser.setUserLevel(user.getUserLevel());
                userMapper.updateById(existingUser);

                result.put("status", "restore");
                result.put("message", "恢复已删除用户成功");
            } else {
                // 已存在未删除的用户
                result.put("status", "exists");
                result.put("message", "手机号已被注册");
            }
        } else {
            // 新增用户时设置加密后的密码
            user.setPassword(encodedPassword); // 使用加密密码
            userMapper.insert(user);
            result.put("status", "created");
            result.put("message", "用户注册成功");
        }

        return result;
    }

    @Override
    public Map<String, Object> updateUser(User user) {
        Map<String, Object> result = new HashMap<>();

        // 查询是否存在相同手机号的其他用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", user.getPhone())
                .ne("user_id", user.getUserId()); // 排除当前用户本身

        User existing = userMapper.selectOne(queryWrapper);

        if (existing != null) {
            result.put("status", "duplicate");
            result.put("message", "手机号已被其他用户占用，无法修改");
            return result;
        }

        // 构建更新语句（注意：此处未涉及密码修改，如需修改密码需单独处理并加密）
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", user.getUserId())
                .set("username", user.getUsername())
                .set("name", user.getName())
                .set("phone", user.getPhone())
                .set("status", user.getStatus())
                .set("role_id", user.getRoleId())
                .set("user_level", user.getUserLevel());

        userMapper.update(null, updateWrapper);

        result.put("status", "success");
        result.put("message", "用户信息更新成功");
        return result;
    }

    @Override
    public void deleteUser(Integer userId) {
        // 逻辑删除用户：将 is_deleted 设置为 1
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId)
                .set("is_deleted", 1)
                .set("status", 0);
        userMapper.update(updateWrapper);
    }

    @Override
    public Map<String, Object> updatePassword(Integer userId, String oldPassword, String newPassword) {
        Map<String, Object> result = new HashMap<>();

        // 1. 查询用户
        User user = userMapper.selectById(userId);
        if (user == null) {
            result.put("status", "error");
            result.put("message", "用户不存在");
            return result;
        }

        // 2. 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            result.put("status", "error");
            result.put("message", "旧密码不正确");
            return result;
        }

        // 3. 加密新密码并更新
        String encodedPassword = passwordEncoder.encode(newPassword);
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId)
                .set("password", encodedPassword);
        userMapper.update(null, updateWrapper);

        result.put("status", "success");
        result.put("message", "密码修改成功");
        return result;
    }
}